import React, { useEffect, useState } from 'react';
import client from '../../api/client';

import s from './style.module.less';
import 'antd/dist/antd.css';

import { useHistory, useParams } from 'react-router';
// 引入图标
import {
  QuestionCircleOutlined,
  UploadOutlined
} from '@ant-design/icons';

// 引入组件
import {
  PageHeader,
  Tabs,
  Button,
  Statistic,
  Descriptions,
  Form,
  Input,
  Radio,
  Select,
  Cascader,
  DatePicker,
  InputNumber,
  TreeSelect,
  Table,
  Popconfirm,
  Typography,
  Image,
  Popover,
  Upload,
  message
} from 'antd';

// 标签页
const { TabPane } = Tabs;
// 布局设置
const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};
// 设置气泡提示语
const content = (
  <div>
    <p>1--表示实物</p>
    <p>2--表示没有中奖</p>
    <p>3--表示矿石</p>
  </div>
);

export default function Manage() {
  // 用户信息
  const [user, setUser] = useState({});
  // 消耗次数
  const [cost, setCost] = useState(0);
  // 表单数据
  const [tableData, setTableData] = useState([])
  // 页头需要的数据
  let awardSum = 0 // 奖品总数

  const [history, setHistory] = useState([]);
  const [data, setData] = useState({});
  const [awards, setAwards] = useState([]);
  const [curIndex, setCurIndex] = useState(-1);
  const [hideDlg, setHideDlg] = useState(true);

  const params = useParams();
  const paths = useHistory();

  // const getUser = async () => {
  //   const res = await client.get('/api/user?id=' + params.userid);
  //   console.log(res);
  //   setUser(res.data.user);
  //   setHistory(res.data.history);
  // };

  // 获取用户数据
  // useEffect(getUser, [params]);
  const getAwards = async () => {
    let res = await client.get('/api/pool_awards');
    let {
      data: { awards, cost },
    } = res;
    awards.splice(4, 0, {
      award_name: cost + '矿石/次',
      type: 0,
    });
    setTableData(res.data.awards);
    setAwards(awards);
    setCost(cost);
  };
  useEffect(getAwards, [data]);


  // 当前用户信息
  const renderContent = (column = 2) => (
    <Descriptions size="small" column={column}>
      {/* <Descriptions.Item label="当前用户">{user.user_name}</Descriptions.Item>
      <Descriptions.Item label="起始矿石数目">{user.ore_num}</Descriptions.Item> */}
    </Descriptions>
  );

  const Content = ({ children, extra }) => (
    <div className="content">
      <div className="main">{children}</div>
      <div className="extra">{extra}</div>
    </div>
  );

  // 表单信息
  const FormSizeDemo = (e) => {
    const [componentSize, setComponentSize] = useState('default');

    const onFinish = async (values) => {
      const {
        data: { cost },
      } = await client.post('/api/edit_cost', { cost: values.newCost });
      setCost(cost);
    };

    const onFormLayoutChange = ({ size }) => {
      setComponentSize(size);
    };

    return (
      <>
        <Form
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 14,
          }}
          layout="horizontal"
          initialValues={{
            size: componentSize,
          }}
          onValuesChange={onFormLayoutChange}
          size={componentSize}
          onFinish={onFinish}
        >
          {/* <Form.Item label="总奖品数">
            <InputNumber
              style={{
                width: '300px'
              }}
              defaultValue={awardSum}
            />
          </Form.Item> */}
          {/* <Form.Item label="单次抽奖中奖概率">
            <InputNumber
              style={{
                width: '300px'
              }}
            />
          </Form.Item> */}
          <Form.Item name='newCost' label="每次消耗的矿石数目">
            <InputNumber
              style={{
                width: '300px'
              }}
              defaultValue={cost}
            />
          </Form.Item>
          <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 4 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </>
    );
  };

  let probabilitySum = 0
  let awardMap = new Map() //用来储存列入1-8奖池的奖品
  // 增加key，同时移除type：0的项，并计算列入物品类型的中奖值的和
  for (let i = 0; i < tableData.length; i++) {
    tableData[i].key = tableData[i].award_id
    if (tableData[i].type === 0) {
      tableData.splice(i, 1)
    }
    // 注意：这里是把number视为奖池编号，目前并不是按1-8，而是0-3和5-8
    if (tableData[i].type != 0 && tableData[i].number >= 0 || tableData[0].number <= 8) {
      probabilitySum += tableData[i].probability
      awardMap.set(tableData[i].number, tableData[i].award_id) // 奖池号为key，奖品id为value
    }
  }

  // 获取总奖品数目
  awardSum = probabilitySum

  // 计算列入奖池物品的概率值
  for (let i = 0; i < tableData.length; i++) {
    tableData[i].key = tableData[i].award_id
    if (tableData[i].type != 0 && tableData[i].number >= 0 || tableData[0].number <= 8) {
      let point = tableData[i].probability / probabilitySum
      let str = Number(point * 100).toFixed(1) + "%"
      tableData[i].percent = str
    }
  }

  function ImageDemo(record) {
    return (
      <Image
        width={100}
        src={record.src}
      />
    );
  }

  const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{
              margin: 0,
            }}
            rules={[
              {
                required: true,
                message: `Please Input ${title}!`,
              },
            ]}
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  const EditableTable = () => {
    const [form] = Form.useForm();
    const [data, setData] = useState(tableData);
    const [editingKey, setEditingKey] = useState('');

    const isEditing = (record) => record.key === editingKey;

    const edit = (record) => {
      form.setFieldsValue({
        name: '',
        age: '',
        address: '',
        ...record,
      });
      setEditingKey(record.key);
    };

    const cancel = () => {
      setEditingKey('');
    };

    const save = async (key) => {
      try {
        const row = await form.validateFields();
        const newData = [...data];
        const index = newData.findIndex((item) => key === item.key);

        if (index > -1) {
          const item = newData[index];
          newData.splice(index, 1, { ...item, ...row });
          setData(newData);
          setEditingKey('');
        } else {
          newData.push(row);
          setData(newData);
          setEditingKey('');
        }
        await client.post('/api/edit_pool', newData[index]);
        getAwards();
      } catch (errInfo) {
        console.log('Validate Failed:', errInfo);
      }
    };

    const columns = [
      {
        title: '奖品名称',
        dataIndex: 'award_name',
        editable: true,
      },
      {
        title: '上传图片',
        dataIndex: 'award_image',
        width: '180px',
        align: 'center',
        render: (_, record) => {
          const Uploader = () => {
            const props = {
              onChange: info => {
                // console.log(info.fileList);
              },
              accept: 'image/*',
              action: '/api/upload',
              data: {
                award_id: record.award_id,
              },
            };
            return (
              <Upload {...props}>
                <Button icon={<UploadOutlined />}>上传图片</Button>
              </Upload>
            );
          };

          const editable = isEditing(record);
          return editable ? (
            <Uploader />
          ) : (
            <ImageDemo src={record.award_image} />
          );
        },
      },
      {
        title: '奖池编号（1-8）',
        dataIndex: 'number',
        width: '180px',
        align: 'center',
        render: (_, record) => {
          const { Option } = Select;
          function handleChange(value) {
            record.number = Number(value)
            // if (awardMap.has(value)) { // 先判断这个奖品编号是否被占用
            //   if (record.number >= 0) { // 判断要改变的奖品的是否有编号
            //     // 如果有，两者交换编号
            //     let newAwardId = awardMap.get(record.number) // 取出当前要修改的奖品的id （也可直接从record中获取）
            //     let oldAwardId = awardMap.get(value) // 取出另一个要修改的奖品的id
            //     // 重新修改awardMap中的值
            //     awardMap.set(record.number, oldAwardId)
            //     awardMap.set(value, newAwardId)
            //     // api:修改两者的值（交换）
            //     // coding....
            //   } else { // 当前奖品为空值
            //     let newAwardId = record.id
            //     awardMap.set(value, newAwardId)
            //     // api:修改两者的值（填入新的，清空原来的）
            //     // coding....
            //   }
            // } else { // 奖品编号未被占用
            //   if (record.number >= 0) { // 如果当前奖品有编号，则清除
            //     awardMap.set(record.number, "")
            //   }
            //   let newAwardId = record.award_id
            //   awardMap.set(value, newAwardId)
            //   // api：更新该奖品的编号
            //   // coding....
            // }
            // // api：重新刷新表格
            // // coding....
          }

          let showNumber = 1
          if (record.number >= 0 && record.number <= 3) {
            showNumber = record.number + 1
          } else {
            showNumber = record.number
          }
          const editable = isEditing(record);
          return editable ? (
            <Select defaultValue={showNumber} style={{ width: 120 }} onChange={handleChange}>
              <Option value="0">1</Option>
              <Option value="1">2</Option>
              <Option value="2">3</Option>
              <Option value="3">4</Option>
              <Option value="5">5</Option>
              <Option value="6">6</Option>
              <Option value="7">7</Option>
              <Option value="8">8</Option>
            </Select>
          ) : (
            <p>
              {showNumber}
            </p>
          );
        },
      },
      {
        title: () => <span>奖品类型（1-3）<Popover Popover content={content} title="奖品类型说明" > <QuestionCircleOutlined /></Popover></span>,
        dataIndex: 'type',
        width: '180px',
        align: 'center',
        editable: true,
      },
      {
        title: '中奖值（整数）',
        dataIndex: 'probability',
        width: '150px',
        align: 'center',
        editable: true,
      },
      {
        title: '中奖概率',
        dataIndex: 'percent',
        width: '100px',
        align: 'center',
        editable: false,
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width: '100px',
        align: 'center',
        render: (_, record) => {
          const editable = isEditing(record);
          return editable ? (
            <span>
              <a
                href="javascript:;"
                onClick={() => save(record.key)}
                style={{
                  marginRight: 8,
                }}
              >
                保存
              </a>
              <Popconfirm title="确定取消编辑？" onConfirm={cancel} okText="确定" cancelText="取消">
                <a>取消</a>
              </Popconfirm>
            </span>
          ) : (
            <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
              编辑
            </Typography.Link>
          );
        },
      },
    ];
    const mergedColumns = columns.map((col) => {
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: (record) => ({
          record,
          inputType: col.dataIndex === 'age' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: isEditing(record),
        }),
      };
    });
    return (
      <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          bordered
          dataSource={data}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{
            onChange: cancel,
          }}
        />
      </Form>
    );
  };

  // 页头 -- 概览信息
  const extraContent = (
    <div
      style={{
        display: 'flex',
        width: 'max-content',
        justifyContent: 'flex-end',
      }}
    >
      <Statistic title="单次消耗矿石" value={cost} />
    </div>
  );

  return (
    <div className={s.manage}>
      <PageHeader
        className="site-page-header-responsive"
        style={{
          backgroundColor: '#edefef'
        }}
        onBack={() => window.history.back()}
        title="抽奖管理"
        subTitle="Lottery Manage"
        // extra={[
        //   <Button key="3">Operation</Button>,
        //   <Button key="2">Operation</Button>,
        //   <Button key="1" type="primary">
        //     Primary
        //   </Button>,
        // ]}
        footer={
          <Tabs defaultActiveKey="1">
            <TabPane tab="奖品配置" key="1" >
              <EditableTable />
            </TabPane>
            <TabPane tab="其他设置" key="2" >
              <FormSizeDemo />
            </TabPane>
          </Tabs>
        }
      >
        <Content extra={extraContent}>{renderContent()}</Content>
      </PageHeader>
    </div>
  );
}
